from stages import GlobalStage
import CDDB, DiscID

from config import Config

class FetchCDDBId(GlobalStage):
    file = Config['cddbfile']
        
    def __init__(self, shagger):
        GlobalStage.__init__(self, shagger) 
    
    def preamble(self):
        return "Load cddb info"
    
    def canWork(self):       
        return True
    
    def work(self):
        cdrom = DiscID.open(Config['cddevice'])
        disc_id = DiscID.disc_id(cdrom)
        
        (query_status, query_info) = CDDB.query(disc_id)
        if(query_info.__class__ == [].__class__):
            #freedb sometimes has > 1 record.
            query_info = query_info[0]
        print(query_info)
        if(query_info == None):
            self.shagger.log( "Not found in CDDB!")
        #TODO: should prob return false and complain upstream - oh well.
            return True
        else:
            (read_status, read_info) = CDDB.read(query_info['category'], query_info['disc_id'])
            self.shagger.log( "CDDB: %s - %s" % (read_info['DTITLE'], read_info['DYEAR']))
        
        fn = self.filename(self.file)
        
        f = open(fn, "w")
        f.write("%s\n" % read_info['DTITLE'])
        
        for i in range(disc_id[1]):
            f.write( "Track %.02d: %s\n" % (i, read_info['TTITLE' + `i`]))
            
        f.close()
        return True
